<template>
  <div class="course-section">
    <div class="header">
      <el-page-header @back="$router.back()" content="课程内容">
      </el-page-header>
      <el-button type="primary" icon="el-icon-plus" @click="addNewSection">添加阶段</el-button>
    </div>
    <el-card style="margin-top: 20px;">
      <el-tree
        :data="sections"
        :props="defaultProps"
        draggable
        :allow-drop="handleAllowDrop"
        @node-drop="handleNodeDrop"
      >
        <div class="inner" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span v-if="data.sectionName" class="actions">
            <el-button @click="editSection(data)">编辑</el-button>
            <el-button type="primary" @click="addNewLesson(data)">添加课时</el-button>
            <el-button @click="updateStatus(data)">{{ data | statusFilter }}</el-button>
          </span>
          <span v-else class="actions">
            <el-button @click="handleEditLesson(data, node)">编辑</el-button>
            <el-button
              type="success"
              @click="$router.push({
                name: 'course-video',
                params: {
                  courseId
                },
                query: {
                  sectionId: node.parent.id,
                  lessonId: data.id
                }
              })"
            >上传视频</el-button>
            <el-button @click="updateStatus(data)">{{ data | statusFilter }}</el-button>
          </span>
        </div>
      </el-tree>
    </el-card>
    <el-dialog title="章节信息" :visible.sync="visible" width="30%">
      <el-form :model="handleForm">
        <el-form-item prop="courseName" label="课程名称">
          <el-input v-model="handleForm.courseName" disabled></el-input>
        </el-form-item>
        <el-form-item prop="sectionName" label="章节名称">
          <el-input v-model="handleForm.sectionName"></el-input>
        </el-form-item>
        <el-form-item prop="description" label="章节描述">
          <el-input v-model="handleForm.description" type="textarea"></el-input>
        </el-form-item>
        <el-form-item prop="orderNum" label="章节排序">
          <el-input v-model="handleForm.orderNum" type="number">
            <template slot="append">数字控制排序，数字越大越靠后</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" :disabled="loading"  @click="saveOrUpdate">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="statusVisible" width="30%">
      <el-form>
        <div class="status-show">
          <i class="el-icon-info"></i>
          <br>
          <span>当前状态：{{ currentStatusShow }}</span>
        </div>
        <el-form-item label="状态变更为">
          <el-select v-model="status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="statusVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="statusLoading"  @click="statusChange">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="课时基本信息" :visible.sync="lessonVisible" width="30%">
      <el-form :model="lessonForm">
        <el-form-item label="课程名称">
          <el-input disabled v-model="lessonForm.courseName"></el-input>
        </el-form-item>
        <el-form-item label="章节名称">
          <el-input disabled v-model="lessonForm.sectionName"></el-input>
        </el-form-item>
        <el-form-item label="课时名称">
          <el-input v-model="lessonForm.theme"></el-input>
        </el-form-item>
        <el-form-item label="时长">
          <el-input v-model="lessonForm.duration" type="number">
            <template slot="append">分钟</template>
          </el-input>
        </el-form-item>
        <el-form-item label="是否开放试听">
          <el-switch
            v-model="lessonForm.isFree"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item label="课程排序">
          <el-input v-model="lessonForm.orderNum" type="number">
            <template slot="append">数字控制排序，数字越大越靠后</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="lessonVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="lessonLoading"  @click="AddLesson">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import {
  getSectionAndLesson,
  saveOrUpdateSection,
  saveOrUpdateLesson
} from '@/services/course'

const statusOptions = [
  { value: 0, label: '已隐藏' },
  { value: 1, label: '待更新' },
  { value: 2, label: '已更新' }
]

const statusFormat = (info: any) => {
  const statusInfo = statusOptions.find(item => item.value === info.status)
  return statusInfo ? statusInfo.label : ''
}

export default Vue.extend({
  name: 'CourseSectionIndex',
  props: {
    courseId: {
      type: [String, Number],
      required: true
    }
  },
  filters: {
    statusFilter (info: any) {
      return statusFormat(info)
    }
  },
  data () {
    return {
      sections: [],
      defaultProps: {
        children: 'lessonDTOS',
        label (data: any) {
          return data.sectionName || data.theme
        }
      },
      handleForm: {
        courseId: this.courseId,
        courseName: this.$route.query.courseName,
        sectionName: '',
        description: '',
        orderNum: ''
      },
      visible: false,
      loading: false,
      statusVisible: false,
      statusLoading: false,
      options: statusOptions,
      status: 0,
      currentStatusShow: '',
      curStatusInfo: {},
      lessonVisible: false,
      lessonLoading: false,
      lessonForm: {
        courseId: this.courseId,
        courseName: this.$route.query.courseName,
        duration: '',
        isFree: false,
        orderNum: '',
        sectionId: '',
        sectionName: '',
        theme: ''
      }
    }
  },
  created () {
    this.loadSections()
  },
  methods: {
    async loadSections () {
      const { data } = await getSectionAndLesson(this.courseId)
      this.sections = data.data
    },
    addNewSection () {
      this.handleForm = {
        courseId: this.courseId,
        courseName: this.$route.query.courseName,
        sectionName: '',
        description: '',
        orderNum: ''
      }
      this.visible = true
    },
    addNewLesson (data: any) {
      this.lessonForm.sectionId = data.id
      this.lessonForm.sectionName = data.sectionName
      this.lessonVisible = true
    },
    handleAllowDrop (draggingNode: any, dropNode: any, type: any) {
      // draggingNode 拖动的节点
      // dropNode 放置的目标节点
      // type 'prev'、'inner' 和 'next'，分别表示放置在目标节点前、插入至目标节点和放置在目标节点后
      return draggingNode.data.sectionId === dropNode.data.sectionId && type !== 'inner'
    },
    async handleNodeDrop (dragNode: any, dropNode: any) {
      try {
        await Promise.all(dropNode.parent.childNodes.map((item: any, index: number) => {
          if (dragNode.data.lessonDTOS !== undefined) {
            // 阶段
            return saveOrUpdateSection({
              id: item.data.id,
              orderNum: index + 1
            })
          } else {
            // 课时
            return saveOrUpdateLesson({
              id: item.data.id,
              orderNum: index + 1
            })
          }
        }))
        this.$message.success('排序成功')
      } catch (error) {
        console.log(error)
        this.$message.error('排序失败')
      }
    },
    async saveOrUpdate () {
      this.loading = true
      await saveOrUpdateSection(this.handleForm)
      this.loading = false
      this.$message.success('操作成功')
      this.visible = false
      this.loadSections()
    },
    editSection (info: any) {
      this.handleForm = { ...this.handleForm, ...info }
      this.visible = true
    },
    updateStatus (info: any) {
      this.currentStatusShow = statusFormat(info)
      this.curStatusInfo = info
      this.status = parseInt(info.status)
      this.statusVisible = true
    },
    async statusChange () {
      const fn = (this.curStatusInfo as any).sectionName ? saveOrUpdateSection : saveOrUpdateLesson
      await fn({
        data: this.curStatusInfo,
        id: (this.curStatusInfo as any).id,
        status: this.status
      })
      this.statusVisible = false
      this.loadSections()
    },
    async AddLesson () {
      this.lessonLoading = true
      await saveOrUpdateLesson(this.lessonForm)
      this.lessonLoading = false
      this.$message.success('操作成功')
      this.lessonVisible = false
      this.loadSections()
    },
    async handleEditLesson (data: any, node: any) {
      console.log(node)
      this.lessonForm = {
        ...this.lessonForm,
        ...data,
        sectionName: node.parent.data.sectionName
      }
      this.lessonVisible = true
    }
  }
})
</script>

<style lang="scss" scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.inner {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}
::v-deep .el-tree-node__content {
  height: auto;
}
.status-show {
  width: 100%;
  text-align: center;
  font-size: 50px;
  margin-bottom: 20px;
  span {
    font-size: 20px;
  }
}
.el-select {
  width: 80%;
}
</style>
